package com.Wu.costomer.dao;

import com.Wu.DBUtil;
import com.Wu.costomer.model.Customer;
import com.Wu.product.model.Product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class CustomerDao {
public Customer getCustomerByName(String username) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from tb_customer where user_name=?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                Customer customer = new Customer();
                customer.setId(rs.getInt("id"));
                customer.setEmail(rs.getString("email"));
                customer.setMobile(rs.getString("mobile"));
                customer.setPassword(rs.getString("password"));
                customer.setReal_name(rs.getString("real_name"));
                customer.setUser_name(rs.getString("user_name"));
                return customer;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.closeResource(conn, ps, rs);
        }
    return null;
 }



//根据用户名和密码添加会员信息
 public int  addCustomer(String username,String password) {
    Customer customer = getCustomerByName(username);
    if (customer == null) {
        Connection conn = DBUtil.getConnection();
        String sql="INSERT INTO `tb_customer`(`username`,`password`) VALUES(?,?)";
PreparedStatement ps = null;
try{
    ps=conn.prepareStatement(sql);
    ps.setString(1, username);
    ps.setString(2, password);
    //执行并更新数据库，返回数据库受影响的行数
    int num = ps.executeUpdate();
    return num;
}catch(SQLException e){
    throw new RuntimeException(e);
}
finally {
    DBUtil.closeResource(conn, ps, null);
}
    }else {
        //账号已存在，返回0表示失败
        return 0;
    }
 }
}
